package first.forHuaWei;

/**
 * @ClassName MyBlockQueue
 * @description: 实现一个阻塞队列
 * @author: 荣燊
 * @create: 2021-09-14 13:14
 **/
public class MyBlockQueue {
    // 阻塞队列的大小为2
    private Object[] items = new Object[2];
    // 两个锁
    private Object notEmpty = new Object();
    private Object notFull = new Object();
    // 记录值
    int count, putidx, takeidx;

    public void put(Object obj) throws InterruptedException {
        synchronized (notFull) {
            while (count == items.length) {
                notFull.wait();
            }
        }
        items[putidx] = obj;
        // 循环去拿取队列中的值
        if (++putidx == items.length) {
            putidx = 0;
        }
        count++;
        // 加上了1，就可以唤醒空锁
        synchronized (notEmpty) {
            notEmpty.notify();
        }
    }

    public Object take() throws InterruptedException {
        synchronized (notEmpty) {
            while (count == 0) {
                notEmpty.wait();
            }
        }
        Object item = items[takeidx];
        System.out.println(item);
        // 循环去拿取队列中的值
        if (++takeidx == items.length) {
            takeidx = 0;
        }
        synchronized (notFull) {
            notFull.notify();
        }
        return item;
    }

    public static void main(String[] args) throws InterruptedException {
        MyBlockQueue myBlockQueue = new MyBlockQueue();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    myBlockQueue.put("xx");
                    myBlockQueue.put("yy");
                    myBlockQueue.put("zz");
                    myBlockQueue.put("kk");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        myBlockQueue.take();
        myBlockQueue.take();
        myBlockQueue.take();
    }
}
